"""
消息通知模块信号处理
"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from django.utils import timezone
from .models import Notification, NotificationPreference

User = get_user_model()


@receiver(post_save, sender=User)
def create_notification_preference(sender, instance, created, **kwargs):
    """用户创建时自动创建通知偏好设置"""
    if created:
        NotificationPreference.objects.get_or_create(user=instance)


@receiver(post_save, sender=Notification)
def send_notification_immediately(sender, instance, created, **kwargs):
    """通知创建时立即发送"""
    if created and instance.status == Notification.Status.PENDING:
        # 异步发送通知（这里可以集成Celery任务）
        try:
            instance.send_notification()
        except Exception as e:
            # 记录错误但不阻止流程
            print(f"发送通知失败: {e}")